package com.david.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.session.events.SessionCreatedEvent;
import org.springframework.session.events.SessionExpiredEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
/**
 * 依据session的创建来判断当前有多少人在线
 * @author David
 */
@Component
@Slf4j
public class SessionListener {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @EventListener
    public void onSessionCreated(SessionCreatedEvent se) {
        log.info("创建Session成功，Sessionid为：" + se.getSessionId());
        log.info("执行创建session操作，创建前在线人数为：" + (stringRedisTemplate.opsForSet().size("onlineSet") - 1));
        stringRedisTemplate.opsForSet().add("onlineSet", se.getSessionId());
        log.info("执行创建session操作，创建后在线人数为：" + (stringRedisTemplate.opsForSet().size("onlineSet") - 1));

    }

    @EventListener
    public void onSession(SessionExpiredEvent se){
        log.info("Session已过期，Sessionid为：" + se.getSessionId());
        log.info("执行销毁session操作，销毁前在线人数为：" + (stringRedisTemplate.opsForSet().size("onlineSet") - 1));
        stringRedisTemplate.opsForSet().remove("onlineSet", se.getSessionId());
        log.info("执行销毁session操作，销毁后在线人数为：" + (stringRedisTemplate.opsForSet().size("onlineSet") - 1));

    }

}
